<script setup lang="ts">
import OrderRequest from '@/request/orderRequest';
import { useAppStore, useControllerStore } from '@/store';
import to from '@/utils/to';
import { requestPayment } from '@/utils/requestPayment';
import { navigate } from '@/utils/navigate';

interface IState {
  list: IOrderList[];
  originNo: string;
  amount: number;
}

const store = useAppStore();
const state = reactive<IState>({ list: [], originNo: useControllerStore().$state.originNo, amount: 0 });

onLoad((options) => {
  if (!options) return;
  if (!options.scene) return;
  state.originNo = options.originNo ? options.originNo : decodeURIComponent(options.scene).split('=')[1];
  useControllerStore().$patch({ originNo: state.originNo });
  if (!store.$state.token) return;
  fetchListOrderByOriginNo();
});

onShow(() => {
  if (!store.$state.token) return;
  if (!useControllerStore().$state.originNo) return;
  fetchListOrderByOriginNo();
});

// 根据OriginNo获得订单列表信息
const fetchListOrderByOriginNo = () => {
  OrderRequest.ListOrderByOriginNo({ originNo: state.originNo, hasLoading: true }).then((res) => {
    state.list = res.data.list;
    state.amount = res.data.list.reduce((accumulator, currentValue) => (accumulator + currentValue.payState === 4 ? currentValue.lastAmount : currentValue.realAmount), 0);
  });
};

// 支付订单
const handlePayTheOrder = () => {
  OrderRequest.ScanToPayWaitOrder({ originNo: state.originNo, openId: store.$state.userInfo.openId, hasLoading: true }).then(async (res) => {
    const [payErr] = await to(requestPayment({ ...res.data, provider: 'wxpay', orderInfo: '' }));
    if (payErr) return;
    navigate({ type: 'switchTab', url: '/pages/order/index' });
  });
};
</script>

<template>
  <view class="h-screen bg-white" v-if="!useAppStore().$state.token && state.originNo">
    <NotLogged :path="`/subcontract/home/paymentByOthers/index?originNo=${state.originNo}`" />
  </view>
  <view v-else class="c-pd overflow-scroll" :style="{ paddingBottom: store.$state.systemInfo.safeAreaInsets!.bottom + 50 + 12 + 'px' }">
    <OrderListCard v-for="item in state.list" :key="item.originNo" :orderInfo="item" :isBtn="false" />
    <van-empty v-if="state.list.length === 0" description="暂无数据" />
  </view>
  <view v-if="state.amount" class="h-50px bg-white w-screen pos-fixed left-0 bottom-0 z-99" :style="{ paddingBottom: store.$state.systemInfo.safeAreaInsets!.bottom + 'px' }">
    <van-divider hairline custom-style="margin: 0" />
    <view class="h-full w-full py-4px px-12px box-border flex justify-between items-center">
      <view class="flex flex-1 h-full">
        <view class="flex-col flex justify-center">
          <view class="text-red">
            ¥<text class="text-20px fw-bold ml-4px">{{ state.amount }}</text>
          </view>
        </view>
      </view>
      <view class="h-90% c-br c-bg flex items-center justify-center text-white px-30px c-text-16" @click="handlePayTheOrder">支付订单</view>
    </view>
  </view>
</template>
